<!DOCTYPE html>
<html lang="zh-cn">
    <head>
        <meta charset="utf-8"/>
        <!--<base href="http://www.w3school.com.cn/i/" />-->
        <style>
            html, body {
                display: block;
                height: 100%;
                overflow: hidden;
                margin: 0;
                padding: 0;
            }

            body {
                background: #12c2e9;
                /* fallback for old browsers */
                background: -webkit-linear-gradient(to right, #f64f59, #c471ed, #12c2e9);
                /* Chrome 10-25, Safari 5.1-6 */
                background: linear-gradient(to right, #f64f59, #c471ed, #12c2e9);
                /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
            }

            .loading {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                display: flex;
                height: 100%;
                align-items: center;
                z-index: 99999;
            }

            .page {
                display: flex;
                height: 100%;
            }

            .page-tree {
                width: 240px;
                height: 100%;
                list-style: none;
                overflow-y: auto;
            }

            .page-tree::-webkit-scrollbar {
                width: 6px;
                background-color: #0b0f111c;
            }

            .page-tree::-webkit-scrollbar-thumb {
                box-shadow: none;
                border-radius: 3px;
                background-color: #00000014;
            }

            .page-tree-item {
                display: block;
                color: white;
            }

            .page-tree-item a {
                display: block;
                padding: 1em;
                background-color: transparent;
                color: aliceblue;
            }

            .page-tree-item a:hover {
                color: #fff;
                background-color: #16212638;
            }

            .page-tree-item:not(:last-child) {
                border-bottom: 1px solid #ffffff29;
            }

            .page-editor {
                height: 100%;
                flex: 1;
            }

            #editor {
                overflow: hidden;
                height: 100%;
            }

            #editor[data-mode="read"] {
                overflow-y: auto;
            }

            #editor .tui-editor-contents {
                margin: 10px;
                font-size: 14px;
                background-color: #ffffff2e;
                padding: 20px;
                border-radius: 10px;
            }

            #save-btn {
                display: block;
                font-size: 14px;
                background-color: #2784e6;
                color: white;
                line-height: 34px;
                padding: 0 2em;
                border-radius: 3px;
                cursor: pointer;
            }

            .Save {
                background-image: url('data:image/svg+xml;utf8,<svg aria-hidden="true" viewBox="0 0 36 36" xmlns="http://www.w3.org/2000/svg"><path d="M6 14l8 8L30 6v8L14 30l-8-8v-8z" fill="black"></path></svg>');
                background-repeat: no-repeat;
                background-position: 50% 50%;
                background-size: 16px auto;
            }
        </style>
    </head>
    <body>
        <div class="loading">
            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="margin: auto; background: none; display: block; shape-rendering: auto;" width="50px" height="50px" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid">
                <circle cx="50" cy="50" r="30" stroke="rgba(NaN, NaN, NaN, 0)" stroke-width="10" fill="none"></circle>
                <circle cx="50" cy="50" r="30" stroke="#39ad11" stroke-width="8" stroke-linecap="round" fill="none" transform="rotate(57.2379 50 50)">
                    <animateTransform attributeName="transform" type="rotate" repeatCount="indefinite" dur="1.7857142857142856s" values="0 50 50;180 50 50;720 50 50" keyTimes="0;0.5;1"></animateTransform>
                    <animate attributeName="stroke-dasharray" repeatCount="indefinite" dur="1.7857142857142856s" values="18.84955592153876 169.64600329384882;94.2477796076938 94.24777960769377;18.84955592153876 169.64600329384882" keyTimes="0;0.5;1"></animate>
                </circle>
            </svg>
        </div>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/codemirror.min.css"/>
        <link rel="stylesheet" href="https://uicdn.toast.com/editor/latest/toastui-editor.min.css"/>
        <link rel="stylesheet" href="https://uicdn.toast.com/tui-color-picker/latest/tui-color-picker.min.css"/>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/styles/github.min.css"/>
        <div class="page">
            <ul class="page-tree"></ul>
            <div class="page-editor">
                <div id="editor"></div>
            </div>
        </div>
        <x-modal title="Important!">
            <p>This is some really important stuff</p>
        </x-modal>
        <script src="https://uicdn.toast.com/editor/latest/toastui-editor-all.min.js"></script>
        <script src="https://uicdn.toast.com/editor-plugin-color-syntax/latest/toastui-editor-plugin-color-syntax.min.js"></script>
        <script src="https://uicdn.toast.com/editor-plugin-code-syntax-highlight/latest/toastui-editor-plugin-code-syntax-highlight-all.min.js"></script>
        <script src="../js/indexdb.js"></script>
        <script src="../js/mdnote.js"></script>
        <script src="../js/components/dialog.mjs"></script>
    </body>
    <script>
        (async()=>{
            const isJsonEqual = (a,b)=>{
                const keys = [...new Set(Object.keys(a).concat(Object.keys(b)))];
                for (let i = 0, k = keys.length; i < k; i++) {
                    const key = keys[i];
                    if (a[key] !== b[key]) {
                        return false
                    }
                }
                return true
            }
            ;
            const database = new IndexDB('markdown_database',2);
            const tables = await database.init([{
                name: 'article',
                params: {
                    keyPath: "id",
                    autoIncrement: true
                },
                indexes: [{
                    name: 'idIndex',
                    key: 'id',
                    unique: true
                }, {
                    name: 'hrefIndex',
                    key: 'href',
                    unique: true
                }]
            }, {
                name: 'rules',
                params: {
                    keyPath: "id",
                    autoIncrement: true
                },
                indexes: [{
                    name: 'idIndex',
                    key: 'id',
                    unique: true
                }, {
                    name: 'hostIndex',
                    key: 'host',
                    unique: true
                }]
            }]);
            const article = database.choose('article');
            const init = function(page, mode) {
                const {Editor} = toastui;
                const editorElement = document.getElementById('editor');
                const setEditorMode = (mode)=>{
                    editorElement.setAttribute("data-mode", mode);
                }
                ;

                const {colorSyntax, codeSyntaxHighlight} = Editor.plugin;

                const createLastButton = (text)=>{
                    const button = document.createElement('button');
                    button.className = text;
                    return button;
                }
                ;
                const options = {
                    el: editorElement,
                    initialValue: page.article.content,
                    height: '100%',
                    linkAttribute: {
                        target: '_blank',
                        contenteditable: 'false',
                        rel: 'noopener noreferrer'
                    }
                };
                const writeOptions = {
                    initialEditType: 'markdown',
                    previewStyle: 'tab',
                    //previewStyle: 'vertical',
                    plugins: [colorSyntax, codeSyntaxHighlight],
                    toolbarItems: ['heading', 'bold', 'italic', 'strike', 'divider', 'hr', 'quote', 'divider', 'ul', 'ol', 'task', 'indent', 'outdent', 'divider', 'table', 'image', 'link', 'divider', 'code', 'codeblock', 'divider', // Using Option: Customize the last button
                    {
                        type: 'button',
                        options: {
                            el: createLastButton('Save'),
                            //command: 'Bold',
                            event: 'save',
                            tooltip: '保存'
                        }
                    }]
                };
                const config = (mode === 'read' ? options : Object.assign(options, writeOptions));
                const editor = mode === 'read' ? Editor.factory(Object.assign({
                    viewer: true,
                }, options)) : new Editor(config);
                setEditorMode(mode);

                editor.eventManager.addEventType('save');
                editor.eventManager.listen('save', function() {
                    const _page = Object.assign({
                        content: editor.getCurrentModeEditor().getValue()
                    }, page.article);
                    article.add(_page).then(()=>{
                        console.log('add succ');
                        document.querySelector('x-modal').alert('添加成功');
                    }
                    ).catch((err)=>{
                        console.log('add failed', err);
                        return article.getByIndex('hrefIndex', _page.href).then((__page)=>{
                            console.log('__page', __page);
                            const seted = article.set({
                                ..._page,
                                id: __page.id
                            });
                            document.querySelector('x-modal').alert('保存成功', (e)=>{
                                //alert('clicked');
                                console.log(e);
                            }
                            );
                        }
                        );
                    }
                    );
                });
            };
            const showList = async()=>{
                const all = await article.getAll(null, 0, 50);
                const tree = document.querySelector('.page-tree');
                if (all && all.length) {
                    all.forEach((one)=>{
                        const li = document.createElement('li');
                        const value = one.value;
                        li.innerHTML = `<div><a href="#id=${one.key}">${value.title}</a></div>`;
                        li.className = 'page-tree-item';
                        tree.appendChild(li);
                    }
                    );
                }
                tree.addEventListener('click', async(e)=>{
                    if (e.target.tagName === 'A') {
                        const url = new URL(e.target.href.replace('#', '?'));
                        const id = url.searchParams.get('id');
                        const one = await article.get(Number(id));
                        init({
                            article: one
                        }, 'read');
                    }
                }
                , false);
            }
            ;
            const saveRule = async(page)=>{
                const rules = database.choose('rules');
                let added = await rules.getByIndex('hostIndex', page.rule.host);
                if (added) {
                    if (!isJsonEqual(added, {
                        id: added.id,
                        ...page.rule
                    })) {
                        const seted = await rules.set({
                            ...page.rule,
                            id: added.id
                        });
                        console.log('updated rule', seted);
                        return
                    }
                    return
                }
                added = await rules.add(page.rule);
                console.log('added rule', added);
            }
            ;
            const bus = new PostMsg(window.opener || parent);

            bus.send('ready', null);
            bus.on('init', async(page)=>{
                if (page) {
                    await saveRule(page);
                }
                if (page) {
                    init(page, 'write');
                }

                await showList();
                document.querySelector('.loading').style.display = 'none';
            }
            );

            /*
const added = await article.add(page).catch((err) => {
        console.error('add failed', err);
    });
    console.log('added', added);

    const seted = await article.set({
        id: 2,
        title: 'xiefucai',
        content: '32324'
    });
    console.log('seted', seted);

    const deleted = await article.delete(1);
    console.log('deleted', deleted);

    const one = await article.get(2);
    console.log('one', one);

    const two = await article.getByIndex('titleIndex', 'xiefucai');
    console.log('getByIndex', two);

    const all = await article.getAll(null, 0, 5);
    console.log('all', all);
*/

        }
        )();
    </script>
</html>
